package com.pls.servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.pls.action.BaseRequestHandler;
import com.pls.actionAdapter.PlsAdapter;
import com.pls.dao.DAOFactory;
import com.pls.dao.EmployeeDAO;
import com.pls.domain.Employee;
import com.pls.javabeans.EmployeeDetailsBean;
import com.pls.javabeans.SearchBean;

/**
 * Servlet implementation class SearchServlet
 */
@WebServlet("/SearchServlet")
public class SearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Logger logger = Logger.getLogger(SearchServlet.class);

	public SearchServlet() {
		// TODO Auto-generated constructor stub
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	protected void process(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		HttpSession session = request.getSession();
		//Gets the context of the current user
		//Employee currentUser = (Employee) session.getAttribute("user");
		PlsAdapter adapter = new PlsAdapter();
		
		String searchQuery = request.getParameter("searchQuery");
		
		searchQuery = searchQuery.replace(" ", ".");
		
		SearchBean bean = new SearchBean();
		bean = adapter.search(searchQuery);
	
		String json = null;
		json = new Gson().toJson(bean);
		
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(json);
		
		//sysout Tests
		//System.out.println(bean.getSearchResults().get(0).getFirstName());

//		RequestDispatcher goToHome = request
//				.getRequestDispatcher("pageTestForSearch.jsp");
//
//		goToHome.forward(request, response);

		// else {
		//
		// RequestDispatcher logInFailDispatcher = request
		// .getRequestDispatcher("login.jsp");
		// request.setAttribute("errorMessage",
		// "Unauthorized access. Please log in.");
		// logInFailDispatcher.forward(request, response);
		//
		// }

	}
}
